import sys
import pygame
import time
import pandas as pd
import ocrutil
import timeutil
import tkinter.filedialog
import tkinter.messagebox
# 事件
def check_events(settings, recognition_button, ownerInfo_table, carInfo_table, history_table, path, img, select_button):
    """ 响应按键和鼠标事件 """
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            button_clicked = recognition_button.rect.collidepoint(mouse_x, mouse_y)
            select_clicked = select_button.rect.collidepoint(mouse_x, mouse_y)
            if select_clicked:
                root = tkinter.Tk()
                root.title('选择图片')
                img = tkinter.filedialog.askopenfilename()
                root.destroy()
            if button_clicked:
                try:
                    # 获取车牌
                    carnumber = ocrutil.getcn(img)

                    # 转换当前时间 2018-12-11 16:18
                    localtime = time.strftime('%Y-%m-%d %H:%M', time.localtime())
                    settings.carnumber = '车牌号码：' + carnumber

                    # 判断进入车辆是否业主车辆
                    # 获取业主车辆信息（只显示卡未过期）
                    ownerInfo_table = ownerInfo_table[ownerInfo_table['validityDate'] > localtime]
                    owner_carnumbers = ownerInfo_table[['carnumber', 'validityDate']].values
                    carnumbers = ownerInfo_table['carnumber'].values
                    # 获取车辆表信息
                    carInfo_carnumbers = carInfo_table[['carnumber', 'inDate', 'isOwner', 'validityDate']].values
                    cars = carInfo_table['carnumber'].values
                    # 增加车辆信息
                    append_carInfo = {
                        'carnumber': carnumber
                    }
                    # 增加历史信息
                    append_history = {
                        'carnumber': carnumber
                    }
                    carInfo_length = len(carInfo_carnumbers)
                    # 车辆表未有数据
                    if carInfo_length == 0:
                        print('未有车辆数据入场')
                        in_park(owner_carnumbers, carnumbers, carInfo_table, append_carInfo, carnumber, localtime, settings, path)
                    # 车辆表有数据
                    else:
                        if carnumber in cars:
                            # 出停车场
                            i = 0
                            for carInfo_carnumber in carInfo_carnumbers:
                                if carnumber == carInfo_carnumber[0]:
                                    if carInfo_carnumber[2] == 1:
                                        if timeutil.time_cmp(carInfo_carnumber[3], localtime):
                                            print('业主车，自动抬杠')
                                            msgMessage = '业主车，可出停车场'
                                            parkPrice = '业主卡'
                                        else:
                                            print('业主车，但卡已过期，收费抬杠')
                                            # 比较卡有效期时间
                                            price = timeutil.priceCalc(carInfo_carnumber[3], localtime)
                                            msgMessage = '停车费用：' + str(5 * int(price)) + '(提醒业主，卡已到期)'
                                            parkPrice = 5 * int(price)

                                    else:
                                        print('外来车，收费抬杠')
                                        # 比较入场时间
                                        price = timeutil.priceCalc(carInfo_carnumber[1], localtime)
                                        msgMessage = '停车费用：' + str(5 * price)
                                        parkPrice = 5 * int(price)

                                    print(i)
                                    carInfo_table = carInfo_table.drop([i])
                                    # 增加数据到历史表
                                    append_history['inDate'] = carInfo_carnumber[1]
                                    append_history['outData'] = localtime
                                    append_history['price'] = parkPrice
                                    append_history['isOwner'] = carInfo_carnumber[2]
                                    append_history['validityDate'] = carInfo_carnumber[3]
                                    history_table = history_table.append(append_history, ignore_index=True)

                                    settings.comeInTime = '出场时间：' + localtime
                                    settings.message = msgMessage

                                    # 更新车辆表和历史表
                                    pd.DataFrame(carInfo_table).to_excel(path + '停车场车辆表' + '.xlsx', sheet_name='data',
                                                                         index=False, header=True)
                                    pd.DataFrame(history_table).to_excel(path + '停车场历史表' + '.xlsx', sheet_name='data',
                                                                         index=False, header=True)
                                    break
                                i += 1
                        else:
                            # 入停车场
                            print('有车辆表数据入场')
                            if carInfo_length < settings.total:
                                in_park(owner_carnumbers, carnumbers, carInfo_table, append_carInfo, carnumber,
                                        localtime, settings, path)
                            else:
                                print('停车场已满')
                                settings.comeInTime = '进场时间：' + localtime
                                settings.message = '停车场已满，无法进入'
                except Exception as e:
                    print("错误原因：", e)
                    continue
                pass
    return img
# 车辆入停车场
def in_park(owner_carnumbers, carnumbers, carInfo_table, append_carInfo, carnumber, localtime, settings, path):
    if carnumber in carnumbers:
        for owner_carnumber in owner_carnumbers:
            if carnumber == owner_carnumber[0]:
                print('业主车，自动抬杠')
                msgMessage = '提示信息：业主车，可入停车场'
                append_carInfo['isOwner'] = 1
                append_carInfo['validityDate'] = owner_carnumber[1]
                # 退出循环
                break
    else:
        print('外来车，识别抬杠')
        msgMessage = '提示信息：外来车，可入停车场'
        append_carInfo['isOwner'] = 0
    append_carInfo['inDate'] = localtime
    settings.comeInTime = '进场时间：' + localtime
    settings.message = msgMessage
    # 添加信息到车辆表
    carInfo_table = carInfo_table.append(append_carInfo, ignore_index=True)
    # 更新车辆表
    pd.DataFrame(carInfo_table).to_excel(path + '停车场车辆表' + '.xlsx', sheet_name='data',
                                         index=False, header=True)